package com.wgh.order.controller;

import com.wgh.order.converter.OrderConverter;
import com.wgh.order.dto.OrderDTO;
import com.wgh.order.entity.Order;
import com.wgh.order.service.OrderService;
import com.wgh.common.vo.PageResult;
import com.wgh.common.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 订单Controller
 * 提供订单相关的RESTful API接口
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;
    
    @Autowired
    private OrderConverter orderConverter;

    /**
     * 创建订单
     */
    @PostMapping
    public Result<OrderDTO> createOrder(@RequestBody OrderDTO orderDTO) {
        try {
            // 转换DTO为实体
            Order order = orderConverter.dtoToOrder(orderDTO);
            // 调用服务层创建订单
            Order createdOrder = orderService.createOrder(order);
            // 转换实体为DTO并返回
            return Result.success(orderConverter.orderToDto(createdOrder));
        } catch (Exception e) {
            return Result.error("创建订单失败：" + e.getMessage());
        }
    }

    /**
     * 获取订单详情
     */
    @GetMapping("/{orderId}")
    public Result<OrderDTO> getOrderDetail(@PathVariable Long orderId) {
        try {
            Order order = orderService.getOrderDetail(orderId);
            if (order == null) {
                return Result.error("404", "订单不存在");
            }
            // 转换实体为DTO并返回
            return Result.success(orderConverter.orderToDto(order));
        } catch (Exception e) {
            return Result.error("获取订单详情失败：" + e.getMessage());
        }
    }

    /**
     * 根据订单编号查询订单
     */
    @GetMapping("/sn/{orderSn}")
    public Result<OrderDTO> getOrderBySn(@PathVariable String orderSn) {
        try {
            Order order = orderService.getOrderBySn(orderSn);
            if (order == null) {
                return Result.error("404", "订单不存在");
            }
            // 转换实体为DTO并返回
            return Result.success(orderConverter.orderToDto(order));
        } catch (Exception e) {
            return Result.error("查询订单失败：" + e.getMessage());
        }
    }

    /**
     * 根据用户ID查询订单列表
     */
    @GetMapping("/user/{userId}")
    public Result<List<OrderDTO>> getOrdersByUserId(
            @PathVariable Long userId,
            @RequestParam(required = false) Integer orderStatus) {
        try {
            List<Order> orders = orderService.getOrdersByUserId(userId, orderStatus);
            // 转换实体列表为DTO列表并返回
            return Result.success(orderConverter.orderListToDtoList(orders));
        } catch (Exception e) {
            return Result.error("获取用户订单列表失败：" + e.getMessage());
        }
    }

    /**
     * 分页查询订单列表
     */
    @GetMapping("/page")
    public Result<PageResult<OrderDTO>> pageOrders(
            @RequestParam Map<String, Object> params,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            PageResult<Order> orderPage = orderService.pageOrders(params, pageNum, pageSize);
            if (orderPage == null || orderPage.getList() == null) {
                return Result.success(new PageResult<>(pageNum, pageSize, 0L, new ArrayList<>()));
            }
            // 转换实体列表为DTO列表
            List<OrderDTO> orderDTOs = orderConverter.orderListToDtoList(orderPage.getList());
            // 创建新的PageResult对象
            PageResult<OrderDTO> dtoPage = new PageResult<>(
                    orderPage.getPageNum(),
                    orderPage.getPageSize(),
                    orderPage.getTotal(),
                    orderPage.getTotalPage(),
                    orderDTOs
            );
            return Result.success(dtoPage);
        } catch (Exception e) {
            return Result.error("分页查询订单失败：" + e.getMessage());
        }
    }

    /**
     * 取消订单
     */
    @PutMapping("/{orderId}/cancel")
    public Result<Boolean> cancelOrder(
            @PathVariable Long orderId,
            @RequestParam Long userId) {
        try {
            boolean result = orderService.cancelOrder(orderId, userId);
            if (result) {
                return Result.success(true);
            } else {
                return Result.error("取消订单失败");
            }
        } catch (Exception e) {
            return Result.error("取消订单失败：" + e.getMessage());
        }
    }

    /**
     * 支付订单
     */
    @PutMapping("/{orderId}/pay")
    public Result<Boolean> payOrder(
            @PathVariable Long orderId,
            @RequestParam Integer payType,
            @RequestParam String transactionId) {
        try {
            boolean result = orderService.payOrder(orderId, payType, transactionId);
            if (result) {
                return Result.success(true);
            } else {
                return Result.error("订单支付失败");
            }
        } catch (Exception e) {
            return Result.error("订单支付失败：" + e.getMessage());
        }
    }

    /**
     * 确认收货
     */
    @PutMapping("/{orderId}/confirm")
    public Result<Boolean> confirmReceipt(
            @PathVariable Long orderId,
            @RequestParam Long userId) {
        try {
            boolean result = orderService.confirmReceipt(orderId, userId);
            if (result) {
                return Result.success(true);
            } else {
                return Result.error("确认收货失败");
            }
        } catch (Exception e) {
            return Result.error("确认收货失败：" + e.getMessage());
        }
    }

    /**
     * 删除订单
     */
    @DeleteMapping("/{orderId}")
    public Result<Boolean> deleteOrder(
            @PathVariable Long orderId,
            @RequestParam Long userId) {
        try {
            boolean result = orderService.deleteOrder(orderId, userId);
            if (result) {
                return Result.success(true);
            } else {
                return Result.error("删除订单失败");
            }
        } catch (Exception e) {
            return Result.error("删除订单失败：" + e.getMessage());
        }
    }

    /**
     * 更新订单状态
     */
    @PutMapping("/{orderId}/status")
    public Result<Boolean> updateOrderStatus(
            @PathVariable Long orderId,
            @RequestParam Integer orderStatus) {
        try {
            boolean result = orderService.updateOrderStatus(orderId, orderStatus);
            if (result) {
                return Result.success(true);
            } else {
                return Result.error("更新订单状态失败");
            }
        } catch (Exception e) {
            return Result.error("更新订单状态失败：" + e.getMessage());
        }
    }

    /**
     * 批量查询订单详情
     */
    @GetMapping("/list")
    public Result<List<OrderDTO>> getOrderListByIds(@RequestParam List<Long> ids) {
        try {
            List<Order> orders = orderService.listByIds(ids);
            // 转换实体列表为DTO列表并返回
            return Result.success(orderConverter.orderListToDtoList(orders));
        } catch (Exception e) {
            return Result.error("批量查询订单失败：" + e.getMessage());
        }
    }
}